import 'package:flutter/material.dart';
import 'package:flutter_wildfire/flutter_wildfire.dart';
import 'package:dio/dio.dart';
import 'package:overlay_support/overlay_support.dart';
import '../cmomon/global.dart';
import '../models/index.dart';
import '../cmomon/userModel.dart';
import 'package:provider/provider.dart';

class PassportMobile extends StatefulWidget {
  PassportMobile({Key key}) : super(key: key);

  _PassportMobileState createState() => _PassportMobileState();
}

class _PassportMobileState extends State<PassportMobile> {
  bool isPhoneVerification = false;
  String _codeCountdownStr = '获取验证码';
  int _countdownNum = 59;
  String _codeText;
  bool _isFetching = false;
  String _loginBtnStr = '登陆';
  String gUserId, gMobile;
  OverlaySupportEntry loading;

  //手机号的控制器
  TextEditingController phoneController = TextEditingController();
  TextEditingController codeController = TextEditingController();
  FocusNode codeTextFieldNode = FocusNode();

  bool verificationPhone() {
    final allText = phoneController.text.trim();
    RegExp exp = new RegExp(r"^1\d{10}$");
    if (exp.hasMatch(allText)) {
      this.setState(() {
        isPhoneVerification = true;
      });
      return true;
    } else {
      this.setState(() {
        isPhoneVerification = false;
      });
      return false;
    }
  }

  Future<void> initPlatformState() async {
    await FlutterWildfire.disconnect();
    FlutterWildfire.on("connectionStatusChange", connectionStatusChangeHandler);
  }

  connectionStatusChangeHandler(status) {
    /**
       *  int ConnectionStatusRejected = -3;
          int ConnectionStatusLogout = -2;
          int ConnectionStatusUnconnected = -1;
          int ConnectionStatusConnecting = 0;
          int ConnectionStatusConnected = 1;
          int ConnectionStatusReceiveing = 2;
       */
    print('mobile page status = $status');
    if (status == -1) {
      print('连接失败');
      FlutterWildfire.disconnect();
    } else if (status == -2) {
      print('退出');
      // FlutterWildfire.disconnect();
    } else if (status == -6) {
      Scaffold.of(context).showSnackBar(SnackBar(
          content: Text('可能token不对，重新登录试下'),
          action: SnackBarAction(label: '撤销', onPressed: showLoginBtn),
          duration: Duration(milliseconds: 2000)));
      print('可能token不对，重新登录试下');
      // FlutterWildfire.disconnect();
    } else if (status == 1) {
      FlutterWildfire.getUserInfo(gUserId, true).then((myInfoJson) {
        loading.dismiss();
        User user = new User.fromJson(myInfoJson);
        Provider.of<UserModel>(context).user = user;
      });
    }
  }

  showLoginBtn() {
    this.setState(() {
      _isFetching = false;
      _loginBtnStr = '登录';
    });
  }

  @override
  void initState() {
    initPlatformState();
    phoneController.addListener(verificationPhone);
    codeController.addListener(() {
      final code = codeController.text.trim();
      this.setState(() {
        _codeText = code;
      });
    });
    super.initState();
  }

  Future<bool> login(String mobile, String code) async {
    String clientId;
    Response response;
    Dio dio = new Dio();
    FocusScope.of(context).requestFocus(FocusNode());
    final loadingKey = ValueKey('loading overlay');
    loading = showOverlay((context, t) {
      return Opacity(
        opacity: t,
        child: Container(
          color: Colors.black.withAlpha(180),
          child: Center(
            child: SizedBox(
              width: 60.0,
              height: 60.0,
              child: CircularProgressIndicator(),
            ),
          ),
        ),
      );
    }, duration: Duration(seconds: 0), key: loadingKey);

    try {
      clientId = await FlutterWildfire.getClientId();
      String _loginUrl =
          'https://${Global.appServerHost}:${Global.appServerPort}/login';
      response = await dio.post(_loginUrl,
          data: {"clientId": clientId, "mobile": mobile, 'code': code});
      if (response.data['code'] != 0) {
        throw response.data['message'];
      }
      LoginResult result = LoginResult.fromJson(response.data['result']);

      String userId = result.userId;
      String token = result.token;

      Global.profile.token = token;
      Global.profile.lastLogin = mobile;
      gUserId = userId;
      gMobile = mobile;
      await FlutterWildfire.connect(userId, token);
      return true;
    } catch (e) {
      print('error');
      print(e);
      loading.dismiss();
      toast('err: $e');
    } finally {
      // clientId = 'Failed to get client id.';
      // client.close();
    }
    return Future.delayed(Duration(milliseconds: 500), () => true);
  }

  void onLoginHandler() async {
    if (!verificationPhone()) {
      return;
    }
    if (this._codeText.isEmpty) {
      return;
    }
    final allText = phoneController.text.trim();
    this.setState(() {
      _isFetching = true;
      _loginBtnStr = '正在登录...';
    });
    bool _hasLogin = await login(allText, _codeText);
    if (_hasLogin) {
      // Navigator.of(context).pushReplacementNamed(Routes.Home);

    } else {
      this.setState(() {
        _isFetching = false;
        _loginBtnStr = '登录';
      });
    }
    return;
  }

  @override
  void dispose() {
    print('dispose');
    FlutterWildfire.off(
        "connectionStatusChange", connectionStatusChangeHandler);
    phoneController.dispose();
    codeController.dispose();
    // FlutterWildfire.disconnect();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    bool disabledCodeBtn = true;
    bool disabledLoginBtn = true;
    if (isPhoneVerification) {
      disabledCodeBtn = false;
      if (this._codeText != null && this._codeText.trim().isNotEmpty) {
        disabledLoginBtn = false;
        if (_isFetching) {
          disabledLoginBtn = true;
        }
      }
    }
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            SizedBox(
              height: 130.0,
            ),
            Text(
              '手机号登录',
              style: TextStyle(fontSize: 28.0),
            ),
            SizedBox(
              height: 40.0,
            ),
            Row(
              children: <Widget>[
                Text(
                  '手机号',
                  style: TextStyle(fontSize: 20.0),
                ),
                SizedBox(
                  width: 20.0,
                ),
                Expanded(
                  child: TextField(
                    // onEditingComplete: getCodeHandler,
                    controller: phoneController,
                    // obscureText: true, // 隐藏输入
                    keyboardType: TextInputType.phone,
                    cursorColor: Colors.green,
                    // maxLength: 11,

                    decoration: InputDecoration(
                      hintText: '请填写手机号',
                      enabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.transparent)),
                      focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.transparent)),
                      // fillColor: Colors.transparent,
                      // filled: true,
                      // labelText: '手机号',
                    ),
                  ),
                )
                // TextField(

                //   cursorColor: Colors.green,
                //   keyboardType: TextInputType.number,
                //   decoration: InputDecoration(
                //     filled: true,
                //       hintText: '请填写验证码',
                //       prefixText: "验证码    ",
                //       helperText: 'helop',
                //       labelText: 'lable',
                //       prefixStyle:
                //           TextStyle(color: Colors.black, fontSize: 18.0)),
                // ),
              ],
            ),
            SizedBox(
              height: 10.0,
            ),
            Row(
              children: <Widget>[
                Text(
                  '验证码',
                  style: TextStyle(fontSize: 20.0),
                ),
                SizedBox(
                  width: 20.0,
                ),
                Expanded(
                  child: TextField(
                    // onEditingComplete: getCodeHandler,

                    controller: codeController,
                    // obscureText: true, // 隐藏输入
                    keyboardType: TextInputType.phone,
                    cursorColor: Colors.green,

                    decoration: InputDecoration(
                      hintText: '请填写验证码',
                      enabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.transparent)),
                      focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.transparent)),
                      // fillColor: Colors.transparent,
                      // filled: true,
                      // labelText: '手机号',
                    ),
                  ),
                )
                // TextField(

                //   cursorColor: Colors.green,
                //   keyboardType: TextInputType.number,
                //   decoration: InputDecoration(
                //     filled: true,
                //       hintText: '请填写验证码',
                //       prefixText: "验证码    ",
                //       helperText: 'helop',
                //       labelText: 'lable',
                //       prefixStyle:
                //           TextStyle(color: Colors.black, fontSize: 18.0)),
                // ),
              ],
            ),
            SizedBox(
              height: 20.0,
            ),
            Container(
              width: double.infinity,
              child: RaisedButton(
                disabledColor: Colors.green[50],
                color: Colors.green,
                padding: EdgeInsets.symmetric(vertical: 10.0),
                onPressed: disabledLoginBtn ? null : onLoginHandler,
                child: Text(
                  _loginBtnStr,
                  style: TextStyle(color: Colors.white, fontSize: 20.0),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
